package com.example.demo.util;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.demo.config.properties.HuaWeiYunProperties;
import com.obs.services.ObsClient;
import com.obs.services.model.HttpMethodEnum;
import com.obs.services.model.PutObjectResult;
import com.obs.services.model.TemporarySignatureRequest;
import com.obs.services.model.TemporarySignatureResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 华为云存储服务OBS文件上传工具类
 *
 * @author TongDaShuai
 * @since 2021/11/4
 */
@Component
@Slf4j
public class HuaWeiYunUtil {


	private static final String REGEX =  "^(http|https)://((\\w)+(\\.)?)+/";
	@Autowired
	private HuaWeiYunProperties hwyProperties;

	private static HuaWeiYunProperties properties;

	private static ObsClient obsClient;

//	####################### 华为云存储OBS服务配置 #####################
//			# 华为云存储OBS服务配置
//	hwy:
//	obs:
//	endPoint: https://obs.cn-east-3.myhuaweicloud.com
//			# Access Key
//	ak: QOEY6RXKSVFKRBDASRQZ
//    # Secret Key
//	sk: 1t1kSfKTdYehGe1IKiCB7mAn7yXZBHUaIYsrByAI
//	bucketname: wuyou-sh-001
//	maxsizeMB: 10
//			# 文件夹名称
//	keySuffixWithSlash: filedata/
//			# url有效期：3600s
//	expireSeconds: 3600
//			# url前缀
//	urlPrefix: http://f.5u5u5u5u.com/

	static {
//		properties = HuaWeiYunProperties.builder()
//				.endPoint("https://obs.cn-east-3.myhuaweicloud.com")
//				.ak("QOEY6RXKSVFKRBDASRQZ")
//				.sk("1t1kSfKTdYehGe1IKiCB7mAn7yXZBHUaIYsrByAI")
//				.bucketname("wuyou-sh-001")
//				.maxsizeMB(10)
//				.keySuffixWithSlash("filedata/")
//				.expireSeconds(3600)
//				.urlPrefix("http://f.5u5u5u5u.com/").build();
//		obsClient = new ObsClient(properties.getAk(), properties.getSk(), properties.getEndPoint());
//		log.error("[HuaWeiYunUtil] ObsClient初始化完毕");
	}

	@PostConstruct
	public void init() {
		properties = hwyProperties;
		obsClient = new ObsClient(properties.getAk(), properties.getSk(), properties.getEndPoint());
		log.error("[HuaWeiYunUtil] ObsClient初始化完毕");
	}


	/**
	 * 获取可访问的url
	 * @param obsUrl 通过obs上传存储的url
	 */
	public static String getAccessibleUrl(String obsUrl) {
		String _url = obsUrl;
		if (StringUtils.isBlank(_url)) {
			return _url;
		}
		TemporarySignatureRequest request = null;
		TemporarySignatureResponse response = null;
		try {
			request = new TemporarySignatureRequest(HttpMethodEnum.GET, properties.getExpireSeconds());
			// 切割文件路径前的域名
			String[] strs = obsUrl.split(REGEX);
			if (strs == null || strs.length < 1 || strs.length != 2) {
				return _url;
			}
			request.setBucketName(properties.getBucketname());
			request.setObjectKey(strs[1]);

			// 设置图片转码参数
			Map<String,Object> queryParams = new HashMap<String, Object>();
			// queryParams.put("x-image-process", "image/resize,m_fixed,w_100,h_100/rotate,100");
			request.setQueryParams(queryParams);

			response = obsClient.createTemporarySignature(request);
			// 获取支持图片转码的下载链接
			_url = response.getSignedUrl();
		} catch (Exception e) {
			log.error("获取可访问资源路径失败: " + e.getMessage());
			throw e;
		}
		return _url;
	}
}